<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\User;

class UserController extends Controller
{
    //
    public function addOrUpdate(Request $request) {

        $wechat = app('wechat.mini_program');
        $res = $wechat->auth->session($request->code?:'');
        $input = $request->all();
        if(isset($res['errcode']) && $res['errcode'] > 0) return $this->apiError($res['errmsg']);
        $open_id = $res['openid'];
        $validateResult = $this->validateCreateUser($input);
        if ($validateResult["errorCode"] > 0) {
            return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        }

        $user = User::where('openid', $open_id)->first();
        if(empty($user)){
            $user = new User();
            $user->openid = $open_id;
        }
        $user->nick_name = $input['nick_name'];
        $user->profile = $input['profile'];
        if(empty($user->score) || $user->score < $input['score']) {
            $user->score = $input['score'];
        }
        $user->save();
        $data = [
            'user' => $user
        ];


        return $this->apiSuccess($data);
    }

    private function validateCreateUser($input) {
        $nick_name = isset($input['nick_name']) ? $input['nick_name']: '';
        $profile = isset($input['profile']) ? $input['profile']: '';
        $score = isset($input['score']) ? $input['score']: '';
        if(empty($nick_name)){
            return [
                "message" => "昵称不得为空",
                "errorCode" => 5000
            ];
        }
        if(empty($profile)){
            return [
                "message" => "头像不得为空",
                "errorCode" => 5000
            ];
        }
        if(empty($score)){
            return [
                "message" => "分数不得为空",
                "errorCode" => 5000
            ];
        }

        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
